package com.song.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/auth")
public class AuthController {
    @GetMapping("/me")
    public Map<String, Object> me(Authentication authentication) {
        Map<String, Object> res = new HashMap<>();
        if (authentication == null) {
            res.put("authenticated", false);
            return res;
        }
        res.put("authenticated", true);
        res.put("username", authentication.getName());
        List<String> roles = new ArrayList<>();
        for (GrantedAuthority a : authentication.getAuthorities()) roles.add(a.getAuthority());
        res.put("roles", roles);
        List<Map<String, String>> menus = new ArrayList<>();
        if (roles.contains("ROLE_ADMIN")) {
            menus.add(menu("数据概览", "/dashboard"));
            menus.add(menu("建材管理", "/materials"));
            menus.add(menu("客户管理", "/customers"));
            menus.add(menu("订单管理", "/orders"));
            menus.add(menu("报表中心", "/reports"));
        } else {
            menus.add(menu("数据概览", "/dashboard"));
            menus.add(menu("订单管理", "/orders"));
        }
        res.put("menus", menus);
        return res;
    }

    private Map<String, String> menu(String name, String path) {
        Map<String, String> m = new HashMap<>();
        m.put("name", name);
        m.put("path", path);
        return m;
    }
}